# _*_ coding:utf-8 _*_
# @Time  : 2023.01.30
# @Author: zizlee
import copy
import datetime
import json

import pandas as pd
from collections import OrderedDict


def read_file_data():
    df = pd.read_excel('6月员工刷卡记录表.xls')
    df.columns = ['col_%02d' % i for i in range(len(df.columns.tolist()))]
    del df['col_00']
    df['index'] = df.index
    dict_data = df.to_dict(orient='records')
    sorted(dict_data, key=lambda x: x['index'])  # 可排序，因为读取的时候肯定是按行顺序的
    return dict_data


def get_worker_info(dict_data):

    max_row = max(dict_data, key=lambda x: x['index'])
    attendance = OrderedDict()
    last_work_num = None
    person = None
    check_date = '未知'

    for row in dict_data:
        # print(row)
        worker_num, worker_name = None, None

        for k, v in row.items():
            if str(v).find('考勤日期') > -1:
                check_date = v
            if str(v).find('工号') > -1:  # 找到一个新的人员
                _col = 'col_%02d' % (int(k.split('_')[1]) + 1)
                worker_num = row[_col]
                if last_work_num is None:
                    last_work_num = worker_num
                else:
                    attendance[last_work_num]['end_index'] = row['index'] - 1
                    last_work_num = worker_num
                if str(worker_num) not in attendance.keys():
                    attendance[str(worker_num)] = {
                        'work_num': worker_num,
                        'date_index': row['index'] + 1,
                        'start_index': row['index'] + 2
                    }
            if str(v).find('姓名') > -1:
                _col = 'col_%02d' % (int(k.split('_')[1]) + 1)
                worker_name = row[_col]
                if worker_num and str(worker_num) not in attendance.keys():
                    raise ValueError(f'{worker_name}的数据字典不存在')
                person = attendance[str(worker_num)]
                person['work_name'] = worker_name

        if person and row['index'] == max_row['index']:  # 增加最后一个的结束行
            person['end_index'] = max_row['index']
    return attendance, check_date


def parser_worker_data(dict_data, workers):  # 解析数据
    dict_data = {row['index']: row for row in dict_data}
    workers_data = []
    for _, wk in workers.items():
        # print(wk)
        cards = {}
        # 解析日期
        date_row = dict_data.get(wk['date_index'])
        date_row = copy.deepcopy(date_row)
        del date_row['index']
        # date_keys = {v: k for k, v in date_row.items() if k != 'index'}
        # print(date_keys)
        for index in range(wk['start_index'], wk['end_index'] + 1):
            # print(index)
            time_row = dict_data.get(index)
            if time_row:
                for k, v in date_row.items():
                    time_values = time_row.get(k)
                    # print(time_values)
                    if not isinstance(time_values, str):
                        if v not in cards.keys():
                            cards[v] = []
                        continue
                    if v not in cards.keys():
                        cards[v] = [s.strip() for s in time_row.get(k).split('\n') if s.strip()]
                    else:
                        cards[v] += [s.strip() for s in time_row.get(k).split('\n') if s.strip()]
        wk['cards'] = cards
        # print(wk['work_name'], wk['start_index'], wk['end_index'])
        # for k, v in wk['cards'].items():
        #     print(k, v)
        # print()
        del wk['date_index']
        del wk['start_index']
        del wk['end_index']
        workers_data.append(copy.deepcopy(wk))
    return workers_data


def checker_attendance(work_data, check_date):
    check_range = check_date[-21:].split('～')
    month = check_range[0][:8]
    print(check_range, month)
    # 读取配置文件
    with open('configs.json', 'r', encoding='utf8') as f:
        configs = json.load(f)
    configs = {c['work_num']: c for c in configs}
    for w in work_data:
        if int(w['work_num']) in [12, 14, 17]:
            continue
        sorted(w['cards'])
        for dt, records in w['cards'].items():
            c_date = datetime.datetime.strptime(f'{month}{dt}', '%Y-%m-%d').strftime('%Y-%m-%d')
            if len(records) < 1:
                # 今日休息
                continue
            has_1, has_2, has_3, has_4 = (False for _ in range(4))
            t1, t2, t3, t4 = ('07:30', '11:30', '13:30', '17:30')
            if int(w['work_num']) in [26]:
                t1, t2, t3, t4 = ('08:00', '12:00', '14:00', '18:00')
            for rd in records:
                if rd <= t1:
                    has_1 = True
                if rd >= t4:
                    has_4 = True
                if t2 <= rd <= t3:
                    has_2 = True
                    has_3 = True
            if 2 <= len(records) <= 3:
                if has_1 and has_2:
                    has_3, has_4 = True, True
                if (has_2 or has_3) and has_4:
                    has_1, has_2, has_3 = True, True, True

            else:
                has_2 = False
                has_3 = False
                middle = list(filter(lambda x: t2 <= x <= t3, records))
                if len(middle) >= 2:
                    has_2 = True
                    has_3 = True

            # if not has_1:
            #     print(f'\033[0;32m 工号={w["work_num"]},姓名={w["work_name"]}无{c_date}早上班卡! \033[0m')
            # if not all([has_2, has_3]):
            #     print(f'\033[1;33m 工号={w["work_num"]},姓名={w["work_name"]}无{c_date}中午两次卡! \033[0m')
            # if not has_4:
            #     print(f'\033[0;32m 工号={w["work_num"]},姓名={w["work_name"]}无{c_date}晚下班卡! \033[0m')
            if not all([has_1, has_2, has_3, has_4]):
                print(f'\033[0;32m 工号={w["work_num"]},姓名={w["work_name"]} {c_date}\033[0m')


if __name__ == '__main__':
    file_data = read_file_data()
    worker_info, file_date = get_worker_info(file_data)
    workers = parser_worker_data(file_data, worker_info)
    checker_attendance(workers, file_date)



    # for w in workers:
    #     del w['cards']
    #     w['time1'] = '07:30'
    #     w['time2'] = '11:30'
    #     w['time3'] = '13:30'
    #     w['time4'] = '17:30'
    # with open('configs.json', 'w', encoding='utf8') as f:
    #     json.dump(workers, f, indent=2, ensure_ascii=False)

